package cookie;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "LastAccessServlet",urlPatterns = "/LastAccessServlet")
public class LastAccessServlet extends HttpServlet {
    private static final long serialVersionUID =1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = req.getCookies();
        boolean flag = false;
        if (cookies.length>0&&cookies!=null){
            for (Cookie cookie:cookies){
                String name = cookie.getName();
                if ("lastTime".equals(name)){
                    flag=true;
                    String value = cookie.getValue();

                    value = URLDecoder.decode(value,"utf-8");
                    resp.getWriter().write("欢迎回来,您上次访问时间为："+value);

                    String str_time = getCurrentDate();
                    cookie.setValue(str_time);
                    cookie.setMaxAge(60*60*24*30);
                    resp.addCookie(cookie);
                    break;
                }
            }
        }

        if (cookies==null || cookies.length==0 || flag==false){
            String str_date = getCurrentDate();
            Cookie cookie = new Cookie("lastTime",str_date);

            cookie.setMaxAge(60*60*24*30);
            resp.addCookie(cookie);
            resp.getWriter().write("您好，欢迎您首次访问");
        }
    }


    private String getCurrentDate() throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat timesdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String str_time = timesdf.format(date);
        str_time = URLEncoder.encode(str_time,"utf-8");
        return str_time;
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, ServletException {
        super.doPost(req, resp);
    }
}
